package com.lyj.cloud.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * 自定义实现UserDetailsService,获取用户及权限
 * 
 * @author sunshine
 * 
 */
@Component
//@Transactional
public class CustomUserDetailsService implements UserDetailsService {

//    @Autowired
//    private UserService userService;

    /**
     * 根据用户名获取登录用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	/*
        Criterion<User> criterion = Restrictions.eq("username",username);
        User user = userService.findOne(criterion);
        if(user == null){
             throw new UsernameNotFoundException("用户名："+ username + "不存在！");
        }

        Collection<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
        List<UsersRoles> urs =  user.getUsersRoles();
//        List<String> roles = new ArrayList<>();
        for(UsersRoles ur : urs){
            String role = ur.getRole().getCode() ;
            Assert.isTrue(!role.startsWith("ROLE_"), role + " cannot start with ROLE_ (it is automatically added)");
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
//            roles.add(role);
        }

//      org.springframework.security.core.userdetails.User.withUsername(username).password(user.getPassword()).roles(roles);

        CustomUserDetails userDetails = new CustomUserDetails(username, user.getPassword(), authorities);
        userDetails.setId(user.getId());
        userDetails.setName(user.getEmployee().getName());
        */
        return loadUserByUsername(username);
    }
}
